import { Application, urlencoded, json } from "express";
import { readFileSync, writeFileSync } from "fs";
import { resolve } from "path";
import { ITodoData } from "../src/js/typings";

export function readFile(path: string): string {
  return readFileSync(resolve(__dirname, path), "utf8");
}
export function writeFile<T>(path: string, data: T): void {
  return writeFileSync(resolve(__dirname, path), JSON.stringify(data));
}

export function fileOperation(path: string, fn?: any): string | void {
  let todoList: ITodoData[] = JSON.parse(readFile("todo.json") || "[]");

  if (!fn) {
    return JSON.stringify(todoList);
  }

  todoList = fn(todoList);
  writeFile<ITodoData[]>(path, todoList);
}
export function CORS(ctx: Application) {
  ctx.use(urlencoded({ extended: false }));
  ctx.use(json());
  ctx.all("*", (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-methods", "POST,GET,PUT,DELETE,OPTINS");
    next();
  });
}
